package com.example.smartmedicalsystem.controller;

import com.example.smartmedicalsystem.entity.Medicine;
import com.example.smartmedicalsystem.repository.MedicineRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/medicine")
@RequiredArgsConstructor
public class MedicineController {
    private final MedicineRepository medicineRepository;

    @GetMapping
    public List<Medicine> getAllMedicines() {
        return medicineRepository.findAll();
    }

    @PostMapping("/{id}/deduct")
    public ResponseEntity<?> deductStock(
            @PathVariable Long id,
            @RequestParam int quantity) {
        Medicine medicine = medicineRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("药品不存在"));
        if (medicine.getStock() < quantity) {
            return ResponseEntity.badRequest().body("库存不足");
        }
        medicine.setStock(medicine.getStock() - quantity);
        return ResponseEntity.ok(medicineRepository.save(medicine));
    }
}